package com.redis.Cachebreakdown;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Random;

/**
 * @author liyanhao
 * @Date 2023-02-14 23:24
 */
@Service
public class RedisCachebreakdown {
    @Autowired
    private RedisTemplate redisTemplate;
    public Object get(String key) {
        //缓存中获取数据
        Object cacheValue = redisTemplate.opsForValue().get(key);
        //缓存为空
        if (StringUtils.isEmpty(cacheValue)) {
            //从存储中获取
            String storageValue = "数据库中的数据";
            redisTemplate.opsForValue().set(key, storageValue);
            //设置一个过期时间（300~600之间的一个随机数）
            int expireTime = new Random().nextInt(300) + 300;
            if (storageValue == null) {
                redisTemplate.expire(key, Duration.ofSeconds(expireTime));
            }
            return storageValue;
        }else {
            //缓存非空
            return cacheValue;
        }
    }
}
